﻿using System;
using System.Windows.Forms;

namespace VirusCleaner.Update
{
    public partial class FrmUpdate : Form
    {
        static void Main(string[] args)
        {
            if (args == null) 
                throw new ArgumentNullException("args");
            Application.EnableVisualStyles();
            string file = Application.ExecutablePath;
            string url = @"http://localhost/update.xml";
            if(args.Length > 0)
            {
                file = args[0];
                if(args.Length == 2)
                {
                    url = args[1];
                }
            }
            Application.Run(new FrmUpdate(file,url));
        }

        private System.ComponentModel.BackgroundWorker _backgroundWorker;
        private Label _label1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private readonly System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmUpdate));
            this._lbxUpdate = new System.Windows.Forms.ListBox();
            this._pbrUpdate = new System.Windows.Forms.ProgressBar();
            this._btnCancel = new System.Windows.Forms.Button();
            this._btnUpdate = new System.Windows.Forms.Button();
            this._lblInfo = new System.Windows.Forms.Label();
            this._backgroundWorker = new System.ComponentModel.BackgroundWorker();
            this._label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // _lbxUpdate
            // 
            this._lbxUpdate.FormattingEnabled = true;
            this._lbxUpdate.ItemHeight = 12;
            this._lbxUpdate.Location = new System.Drawing.Point(12, 36);
            this._lbxUpdate.Name = "_lbxUpdate";
            this._lbxUpdate.Size = new System.Drawing.Size(333, 64);
            this._lbxUpdate.TabIndex = 0;
            // 
            // _pbrUpdate
            // 
            this._pbrUpdate.Location = new System.Drawing.Point(12, 106);
            this._pbrUpdate.Name = "_pbrUpdate";
            this._pbrUpdate.Size = new System.Drawing.Size(333, 23);
            this._pbrUpdate.TabIndex = 1;
            // 
            // _btnCancel
            // 
            this._btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this._btnCancel.Location = new System.Drawing.Point(265, 133);
            this._btnCancel.Name = "_btnCancel";
            this._btnCancel.Size = new System.Drawing.Size(80, 26);
            this._btnCancel.TabIndex = 2;
            this._btnCancel.Text = "取消(&C)";
            this._btnCancel.UseVisualStyleBackColor = true;
            this._btnCancel.Click += new System.EventHandler(this.BtnCancelClick);
            // 
            // _btnUpdate
            // 
            this._btnUpdate.DialogResult = System.Windows.Forms.DialogResult.OK;
            this._btnUpdate.Location = new System.Drawing.Point(184, 133);
            this._btnUpdate.Name = "_btnUpdate";
            this._btnUpdate.Size = new System.Drawing.Size(80, 26);
            this._btnUpdate.TabIndex = 2;
            this._btnUpdate.Text = "检查更新(&U)";
            this._btnUpdate.UseVisualStyleBackColor = true;
            this._btnUpdate.Click += new System.EventHandler(this.BtnUpdateClick);
            // 
            // _lblInfo
            // 
            this._lblInfo.AutoSize = true;
            this._lblInfo.Location = new System.Drawing.Point(12, 140);
            this._lblInfo.Name = "_lblInfo";
            this._lblInfo.Size = new System.Drawing.Size(53, 12);
            this._lblInfo.TabIndex = 4;
            this._lblInfo.Text = "速度:{0}";
            this._lblInfo.Visible = false;
            // 
            // backgroundWorker1
            // 
            this._backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.BackgroundWorkerDoWork);
            this._backgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.BackgroundWorkerProgressChanged);
            this._backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.BackgroundWorkerRunWorkerCompleted);
            // 
            // label1
            // 
            this._label1.AutoSize = true;
            this._label1.Location = new System.Drawing.Point(24, 12);
            this._label1.Name = "_label1";
            this._label1.Size = new System.Drawing.Size(101, 12);
            this._label1.TabIndex = 5;
            this._label1.Text = "版本更新程序:{0}";
            // 
            // FrmUpdate
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(357, 165);
            this.Controls.Add(this._label1);
            this.Controls.Add(this._lblInfo);
            this.Controls.Add(this._btnUpdate);
            this.Controls.Add(this._btnCancel);
            this.Controls.Add(this._pbrUpdate);
            this.Controls.Add(this._lbxUpdate);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FrmUpdate";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "自动更新";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmUpdateFormClosing);
            this.Load += new System.EventHandler(this.FrmUpdateLoad);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private bool _isUpdate;
        private Label _lblInfo;
        
        private Button _btnCancel;
        private Button _btnUpdate;
        private ListBox _lbxUpdate;
        private ProgressBar _pbrUpdate;
        private readonly Updater _update;
        private System.Threading.Thread _thread;
        public FrmUpdate(string file,string url):base()
        {
            _update = new Updater(file) {UpdateUrl = url};
            InitializeComponent();
        }
        private void FrmUpdateLoad(object sender, EventArgs e)
        {
            
        }
        private void BtnUpdateClick(object sender, EventArgs e)
        {
                
            if (_btnUpdate.Text.Equals("立即更新(&U)"))
            {
                _lbxUpdate.Items.Add("开始下载,请稍后....");
                _update.StateChanged += UpdateStateChanged;
                _thread = new System.Threading.Thread(x => _update.Update());
                _thread.Start();
            }else
            {
                _pbrUpdate.Style = ProgressBarStyle.Marquee;
                if (_backgroundWorker.IsBusy == false)
                {
                    _backgroundWorker.RunWorkerAsync();
                }
            }
        }
        void UpdateStateChanged(long value, long max, int bytes)
        {
            _pbrUpdate.Maximum = (int)max;
            _pbrUpdate.Value = (int)value;
            _lblInfo.Text = string.Format("速度:{0}/Kbps", bytes / 1024);
            _lbxUpdate.Items[1] = string.Format("正在下载更新包:{0:0%}",value/(double)max);
            if(value.Equals(max))
            {
                _lbxUpdate.Items.Add("更新包下载完成.");
            }            
        }

        private void BtnCancelClick(object sender, EventArgs e)
        {
            Close();
        }

        private void FrmUpdateFormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = MessageBox.Show(this,@"是否退出?","",MessageBoxButtons.YesNo,MessageBoxIcon.Question).Equals(DialogResult.No);
            if (_thread != null && _thread.ThreadState != System.Threading.ThreadState.Stopped)
            {
                _thread.Abort();
            }
        }

        private void BackgroundWorkerDoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            string str = "";
            try
            {
                if (_btnUpdate.Text.Equals("检查更新(&U)"))
                {
                    _isUpdate = _update.CheckUpdate();
                    str = _isUpdate ? String.Format("发现新版本: {0}", _update.GetVersion()) : "当前是最新版本";

                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
            Invoke(new Action<FrmUpdate>(x =>
                                          {
                                              _lbxUpdate.Items.Add(str);
                                              _btnUpdate.Text = _isUpdate ? "立即更新(&U)" : "检查更新(&U)";

                                          }),this);
        }
        private void BackgroundWorkerRunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            _pbrUpdate.Style = ProgressBarStyle.Blocks;
        }

        private void BackgroundWorkerProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            _pbrUpdate.Style = ProgressBarStyle.Continuous;
            _pbrUpdate.Value = e.ProgressPercentage;
        }
    }
}
